<template>
  <div class="sankeyEchart-container" v-loading="loading">
    <!-- 暂无数据 -->
    <noData
      v-show="hasData"
      title="碳排放能源流向分析"
      :subTitle="params.organizationName.value"
      :year="params.queryParams.inventoryYear"
    />
    <div v-show="!hasData" class="chart-box">
      <div class="chart-title">
        <p class="title">碳排放能源流向分析(单位: t CO₂e)</p>
        <p class="sub-title"
          ><span>{{ params.organizationName.value }}</span>
          <el-divider v-if="params.queryParams.inventoryYear" direction="vertical" />
          <span v-if="params.queryParams.inventoryYear"
            >{{ params.queryParams.inventoryYear }}年</span
          >
        </p>
      </div>
      <main>
        <div class="echart-bg">
          <!-- 类型 -->
          <div class="type">
            <p>类型：排放范围</p>
            <p>类型：排放类型</p>
            <p>类型：排放源</p>
          </div>
          <!-- echart - 桑基图 -->
          <div class="sankeyEchart" ref="sankeyEchart"></div>
          <!-- 最大碳排 -->
          <div class="max-carbon-emission">
            <p>最大碳排：{{ sankeyRes.topScope }}</p>
            <p>最大碳排：{{ sankeyRes.topSourceName }}</p>
            <p>最大碳排：{{ sankeyRes.topMaterialName }}</p>
          </div>
          <!-- 背景分割线 -->
          <div class="echart-bg-line">
            <div class="line-item"></div>
            <div class="line-item"></div>
            <div class="line-item"></div>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, inject, ComputedRef, watch, defineProps, computed, onMounted } from 'vue';
import noData from '../../noData/index.vue';
import { useECharts } from '@/hooks/useECharts';
import {
  queryAnalysisParams,
  queryOrgAnalysisSankeyRes
} from '@/apis/eci/visualAnalysis/model/visualAnalysisModel';
import { queryOrgByMaterialItemAnalysis } from '@/apis/eci/visualAnalysis';
import { kgToT } from '@/utils';

interface injectParams {
  queryParams: queryAnalysisParams;
  organizationName: ComputedRef;
}

const sankeyEchart = ref();
const loading = ref(false);
const props = defineProps(['month']);
const params = inject('params') as injectParams;
// 监听(集团，年份，标准)是否发生改变，改变重置 Echart
watch(params.queryParams, () => {
  loadSankeyData();
});
// 监听月份是否发生改变，改变重置 Echart
watch(
  () => props.month,
  () => {
    loadSankeyData();
  }
);

const hasData = computed(() => {
  if (sankeyRes.value.nodes) {
    return sankeyRes.value.nodes.length === 0;
  } else {
    return true;
  }
});
// 第二列块的颜色
const colors2 = [
  '#D1755A',
  '#6C8AA4',
  '#CECEC3',
  '#2EA6A7',
  '#095F6A',
  '#C1D0A7',
  '#2E7C7B',
  '#C7D3C6'
];
// 第三列块的颜色
const colors3 = [
  '#416D67',
  '#E5E4CE',
  '#6C9585',
  '#22384A',
  '#96CFED',
  '#F7C124',
  '#56595A',
  '#C7CACB'
];
const sankeyRes: any = ref([]);
// 请求桑基图数据
const loadSankeyData = async () => {
  try {
    if (params.queryParams.inventoryYear) {
      loading.value = true;
      const res: queryOrgAnalysisSankeyRes = await queryOrgByMaterialItemAnalysis({
        ...params.queryParams,
        dataPeriod: props.month
      });
      const firstLevelArr = ['范围一', '范围二', '范围三'];
      const secondLevelMap: {
        [key: string]: {
          [key2: string]: any;
        };
      } = {};
      const thirdLevelMap: {
        [key: string]: {
          [key2: string]: any;
        };
      } = {};
      const links = res.links.map(item => {
        // 第二第三列的色值
        if (firstLevelArr.includes(item.source)) {
          secondLevelMap[item.target] = {
            value: item.value
          };
        } else {
          thirdLevelMap[item.target] = {
            value: item.value
          };
        }
        return {
          source: item.source,
          target: item.target,
          value: kgToT(Number(item.value))
        };
      });

      const sortedData2: {
        [key: string]: any;
      } = getSortedData(secondLevelMap, colors2);
      console.log('sortedData2', sortedData2);

      const sortedData3: {
        [key: string]: any;
      } = getSortedData(thirdLevelMap, colors3);
      console.log('sortedData3', sortedData3);

      res.nodes.forEach(item => {
        if (item.name === '范围一') {
          item.itemStyle = {
            color: '#53B89E'
          };
        } else if (item.name === '范围二') {
          item.itemStyle = {
            color: '#7CA6AC'
          };
        } else if (item.name === '范围三') {
          item.itemStyle = {
            color: '#8888BD'
          };
        }
        if (sortedData2[item.name]) {
          item.itemStyle = {
            color: sortedData2[item.name].color
          };
        } else if (sortedData3[item.name]) {
          item.itemStyle = {
            color: sortedData3[item.name].color
          };
        }
        console.log('item', item);
      });
      sankeyRes.value = {
        links,
        nodes: res.nodes,
        topMaterialName: res.topMaterialName,
        topScope: res.topScope,
        topSourceName: res.topSourceName
      };
      console.log('碳排放量按组织分布分析-桑基图', sankeyRes.value);
      renderChart(); // 渲染 echarts
    }
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};
onMounted(() => {
  loadSankeyData();
});

const { setOptions } = useECharts(sankeyEchart);
// 桑基图 Echart
const renderSankeyEchart = () => {
  let option: any = {
    tooltip: {
      trigger: 'item',
      triggerOn: 'mousemove'
    },
    series: [
      {
        type: 'sankey',
        left: '0',
        right: 0,
        data: sankeyRes.value.nodes,
        links: sankeyRes.value.links,
        emphasis: {
          focus: 'adjacency'
        },
        levels: [
          {
            depth: 0
          },
          {
            depth: 1
          },
          {
            depth: 2,
            label: {
              show: true,
              position: 'left'
            }
          }
        ],
        lineStyle: {
          color: 'source',
          opacity: 0.6,
          curveness: 0.5
        }
      }
    ]
  };
  return option;
};
function renderChart() {
  const option = renderSankeyEchart();
  setOptions(option);
}

// 将对象排序并设置颜色
function getSortedData(
  levelMap: {
    [key: string]: {
      [key2: string]: any;
    };
  },
  colors: string[]
) {
  // 将对象转换为数组并按值排序
  const sortedArray2 = Object.entries(levelMap).sort(
    (a, b) => parseFloat(b[1].value) - parseFloat(a[1].value)
  );

  // 为每一项添加排序值
  const sortedData2: {
    [key: string]: any;
  } = sortedArray2.reduce((acc, [key, value], index) => {
    acc[key] = { ...value, order: index, color: colors[index % 8] };
    return acc;
  }, {} as { [key: string]: any });

  console.log('getSortedData', getSortedData);
  return sortedData2;
}
</script>

<style lang="scss" scoped>
.sankeyEchart-container {
  height: 100%;
  background: #ffffff;
  box-shadow: 0px 2px 4px 0px rgba(67, 89, 112, 0.08);
  border-radius: 6px;
  .chart-box {
    height: 100%;
    .chart-title {
      height: 70px;
      padding: 13px 20px;
      .title {
        font-size: 14px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 700;
        color: #0a1f33;
        line-height: 22px;
      }
      .sub-title {
        font-size: 12px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        color: #7a8a99;
        line-height: 20px;
      }
    }

    main {
      height: calc(100% - 70px);
      padding: 0 16px 12px;
      // position: relative;
      .echart-bg {
        position: relative;
        height: calc(100% - 12px);
        background: #f8fbfc;
        width: 100%;
        border-radius: 6px;
        border: 1px solid #ebeff2;
        display: flex;
        flex-direction: column;
        padding: 12px 16px;

        .type {
          display: flex;
          justify-content: space-between;
          p {
            font-size: 12px;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            color: #0a1f33;
            line-height: 20px;
          }
        }
        .max-carbon-emission {
          display: flex;

          justify-content: space-between;
          p {
            line-height: 20px;
            font-size: 12px;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            color: #7a8a99;
          }
        }
        .sankeyEchart {
          position: relative;
          z-index: 2;
          flex: 1;
          &::after {
            position: absolute;
            top: 15px;
            left: 0;
            content: '';
            width: 100%;
            height: 1px;
            background-color: #e1e6eb;
          }
          &::before {
            position: absolute;
            bottom: 15px;
            left: 0;
            content: '';
            width: 100%;
            height: 1px;
            background-color: #e1e6eb;
          }
        }

        .echart-bg-line {
          z-index: 1;
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          padding: 0 16px 0;
          width: 100%;
          height: calc(100% - 12px - 64px);
          display: flex;
          // background: red;
          justify-content: space-between;
          .line-item {
            width: 1px;
            height: 100%;
            background-color: #e1e6eb;
            &:nth-child(2) {
              position: relative;
              background-color: transparent !important;
              &::after {
                content: '';
                width: 1px;
                height: 100%;
                position: absolute;
                background-color: #e1e6eb;
                top: 0;
                left: -10px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
